# coding=utf-8

import os
from uuid import uuid1
from time import sleep

from base_tool import WK_PATH,is_mail_address,to_md5,shell,is_domain,get_ip_by_domain,get_host_ip
from config import Config,Caddy_config



def start():
    config_path = os.path.join(WK_PATH,"config.json")

    skip_init_config = "N"
    if os.path.isfile(config_path):
        skip_init_config = input("config file exist, skip ? (Y/N): ")
    if skip_init_config in  ["N","n"]:
        while 1:
            # 收集信息初始化配置
            mail = ""
            while not is_mail_address(mail):
                mail = input("input an email address for login web panel: ")

            password = ""
            password = input("input a password for login web panel: ")
            while len(password) < 3:
                print("password too short!")
                password = input("input a password for login web panel: ")
            
            salt = uuid1().hex
            hashed_password = to_md5(raw=password,mix_text=salt)

            admin_domain = input("input a domain for login web panel: ")
            while not is_domain(admin_domain):
                print("incorrect domain!")
                admin_domain = input("input a domain for login web panel: ")
            
            if get_ip_by_domain(admin_domain) != get_host_ip():
                print("{}({}) now not pointing to {}".format(admin_domain,get_ip_by_domain(admin_domain),get_host_ip()))
                admin_domain = input("input a domain for login web panel: ")

            print(str({
                "mail":mail,
                "password":password,
                "domain":admin_domain
            }))
            ok = input("all info right ? (Y/N): ")
            if ok not in ["Y","y"]:
                continue
            else:
                a = Config().initial(admin_mail=mail,admin_password=hashed_password,admin_salt=salt,admin_domain=admin_domain)
                if a:
                    print("initial config finished")
                break

    
    venv_path = os.path.join(WK_PATH,"venv")

    skip_init_venv = "N"
    if os.path.isdir(venv_path):
        skip_init_venv = input("virtual environment exist, skip ? (Y/N): ")

    if skip_init_venv in  ["N","n"]:
        
        # 开始安装虚拟环境和依赖
        print("initialing virtual environment")
        venv_path = os.path.join(WK_PATH, "venv")
        os.makedirs(venv_path)

        r = shell("python3.7 -m venv {}".format(venv_path))
        pip_bin_path = os.path.join(venv_path, "bin", "pip3.7")
        r = shell("{} install -r {} -i https://pypi.tuna.tsinghua.edu.cn/simple/ && {} install gunicorn -i https://pypi.tuna.tsinghua.edu.cn/simple/ ".format(
            pip_bin_path, 
            os.path.join(WK_PATH, "requirements.txt"),
            pip_bin_path
        ))

    debug_mode = None
    debug_mode = input("running on debug mode? (Y/N)")
    
    if debug_mode in  ["Y","y"]:
        # 打开调试端口
        shell("firewall-cmd --zone=public --add-port=8081/tcp  --permanent")
        shell("firewall-cmd --reload")
        python_bin_path = os.path.join(venv_path, "bin", "python3.7")
        os.system("{} {}".format(python_bin_path,os.path.join(WK_PATH,"wsgi.py")))
    else:
        # 安装 firewalld 并开放 80 和 443端口
        os.system("firewall-cmd --zone=public --add-port=80/tcp  --permanent")
        os.system("firewall-cmd --zone=public --add-port=443/tcp  --permanent")
        os.system("firewall-cmd --reload")
        # 检测 caddyserver 是否已经服务化
        # ./denpendence/caddy_bin
        caddy_bin_path = os.path.join(WK_PATH,"dependence","caddy_bin")
        shell("chmod 777 {}".format(caddy_bin_path))
        caddy_log_path = os.path.join(WK_PATH,"caddy_log.txt")
        caddy_file_path = os.path.join(WK_PATH,"config","caddy","runtime_caddy_file")
        # 建构 caddyserver 配置
        Caddy_config.rebuild()
        # caddyserver 服务化
        with open(os.path.join(WK_PATH,"config","daemon","caddy_bin.service"),"rt",encoding="utf-8")as cs:
            root = os.path.join(WK_PATH,"static")
            t = str(cs.read()).format(caddy_bin_path=caddy_bin_path,root=root,caddy_file_path=caddy_file_path)
            with open(os.path.join("/etc/systemd/system/","caddy_bin.service"),"wt",encoding="utf-8")as s:
                s.write(t)

        # flask_deployer 服务化
        with open(os.path.join(WK_PATH,"config","daemon","flask_app_manager.service"),"rt",encoding="utf-8")as s:
            t = s.read()
            t = t.format(WK_PATH,WK_PATH)
            with open(os.path.join("/etc/systemd/system/","flask_deployer.service"),"wt",encoding="utf-8")as s:
                s.write(t)
        

        os.system("systemctl daemon-reload")
        os.system("systemctl enable flask_deployer")
        os.system("systemctl start flask_deployer")
        os.system("systemctl enable caddy_bin")
        os.system("systemctl start caddy_bin")


def delete():
    try:
        os.system("systemctl daemon-reload")
        os.system("systemctl stop flask_deployer")
        os.system("systemctl stop caddy_bin")
        os.system("systemctl disable flask_deployer")
        os.system("systemctl disable caddy_bin")
        os.remove(os.path.join("/etc/systemd/system/","flask_deployer.service"))
        os.remove(os.path.join("/etc/systemd/system/","caddy_bin.service"))
        os.system("rm -rf {}".format(WK_PATH))
        os.system('echo "finished"')
    except:
        print("error")



if __name__ == "__main__":
    ok = False
    while not ok:
        print("1. start.\n2. delete")
        m = input("which mode ? : ")
        if str(m) == "1":
            start()
            break
        elif str(m) == "2":
            delete()
            break
        else:
            print("incorrect input! please retry.")
